package com.cxb.apipassenger.service;

import com.cxb.internalcommon.constant.CommonStatusEnum;
import com.cxb.internalcommon.constant.TokenConstants;
import com.cxb.internalcommon.dto.ResponseResult;
import com.cxb.internalcommon.dto.TokenResult;
import com.cxb.internalcommon.responese.TokenResponse;
import com.cxb.internalcommon.util.JwtUtils;
import com.cxb.internalcommon.util.RedisPrefixUtils;
import jdk.nashorn.internal.parser.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class TokenService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 刷新Token
     * @param refreshTokenSrc
     * @return
     */
    public ResponseResult refreshToken(String refreshTokenSrc){

        //解析refreshToken
        TokenResult tokenResult = JwtUtils.checkToken(refreshTokenSrc);
        if(tokenResult==null){
            return ResponseResult.fail(CommonStatusEnum.TOKEN_ERROR.getCode(),CommonStatusEnum.TOKEN_ERROR.getValue());
        }
        String phone = tokenResult.getPhone();
        String identity = tokenResult.getIdentity();

        //读取redis的refreshToken
        String refreshTokenKey = RedisPrefixUtils.generatorTokenKey(phone,identity, TokenConstants.REFRESH_TOKEN_TYPE);
        //从Redis获取refreshToken
        String refreshTokenValue = stringRedisTemplate.opsForValue().get(refreshTokenKey);

        //校验
        if((refreshTokenValue.isEmpty()) || (!refreshTokenSrc.trim().equals(refreshTokenValue.trim())))
        {
            return ResponseResult.fail(CommonStatusEnum.TOKEN_ERROR.getCode(),CommonStatusEnum.TOKEN_ERROR.getValue());
        }

        //生成双Token

        String refreshToken = JwtUtils.generatorToken(phone,identity,TokenConstants.REFRESH_TOKEN_TYPE);
        String accessToken = JwtUtils.generatorToken(phone,identity,TokenConstants.ACCESS_TOKEN_TYPE);
        String accessTokenKey = RedisPrefixUtils.generatorTokenKey(phone,identity, TokenConstants.ACCESS_TOKEN_TYPE);

        //加入redis
        stringRedisTemplate.opsForValue().set(accessTokenKey,accessToken,30, TimeUnit.DAYS);
        stringRedisTemplate.opsForValue().set(refreshTokenKey,refreshToken,31, TimeUnit.DAYS);

        TokenResponse tokenResponse =new TokenResponse();
        tokenResponse.setRefreshToken(refreshToken);
        tokenResponse.setAccessToken(accessToken);

        return ResponseResult.success(tokenResponse);
    }
}
